package com.killer.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.killer.conf.OssConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private OssConfig ossConfig;

    private static final String[] SUPPORT_TYPE = {"png", "jpg", "jpeg"};

    private static final long MAX_SIZE=1024*1024*5;

    public String uploadFile(MultipartFile multipartFile) throws IOException {
        //获取原始文件名
        String originName=multipartFile.getOriginalFilename();
        //获取扩展名
        String extName = StringUtils.substringAfterLast(originName, ".");
        //判断上传的文件格式是否支持
        if (!Arrays.asList(SUPPORT_TYPE).contains(extName)) {
            throw new RuntimeException("不支持:" + extName + "格式的文件上传");
        }
        //获取文件长度
        long fileSize=multipartFile.getSize();
        if (fileSize > MAX_SIZE) {
            throw new RuntimeException("不允许上传大于5M的文件");
        }
        //生成文件名
        String fileName = generateFileName(extName);
        ObjectMetadata objectMetadata=new ObjectMetadata();
        objectMetadata.setHeader("originFileName", originName);
        ossClient.putObject(ossConfig.getBucketName(),fileName,multipartFile.getInputStream(), objectMetadata);
        return fileName;
    }

    private String generateFileName(String extName){
        Date date = new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(date)+"/"+ UUID.randomUUID().toString()+"."+extName;
    }

    public InputStream download(String key) {
        OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), key);
        return ossObject.getObjectContent();
    }


    public void deletFile(String fileUrl) {
        ossClient.deleteObject(ossConfig.getBucketName(), fileUrl);
    }
}
